/**
 * 
 */
package com.example.downloadmanagerdemo.download;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * @author careyjwang
 * 
 */
/**
 * 内存级别缓存器，用于减少文件读写次数
 */
public class DownloadMMCache {
	private ByteArrayOutputStream mBufferedOutputStream;
	private RandomAccessFile mRandomAccessFile;
	private long mMaxCachedSize;
	private long mDownloadedSize;
	private String mPackageName;

	public DownloadMMCache(ByteArrayOutputStream outputStream, RandomAccessFile accessFile, long maxCachedSize,
			long downloadedSize, String packageName) {
		mBufferedOutputStream = outputStream;
		mRandomAccessFile = accessFile;
		mMaxCachedSize = maxCachedSize;
		mDownloadedSize = downloadedSize;
		mPackageName = packageName;
	}

	public void write(byte[] temp, int offset, int length) throws IOException {
		mBufferedOutputStream.write(temp, offset, length);
		mDownloadedSize += temp.length;
		if (mBufferedOutputStream.size() > mMaxCachedSize) {
			flush();
		}
	}

	public void flush() throws IOException {
		byte[] data = mBufferedOutputStream.toByteArray();
		mRandomAccessFile.write(data, 0, data.length);
		DownloadRecordHelper.getInstance().writeSavedSize(mDownloadedSize, mPackageName);
		mBufferedOutputStream.reset();
	}

	public void seek(long offset) throws IOException {
		mRandomAccessFile.seek(offset);
	}
}
